// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "QUAD4IntegStressRepository.h"

#include "DBManager/Repository/HDF5/Base/HDF5RepositoryMacro.h"

HDF5_REG_NO_SORT_REPOSITORY (QUAD4IntegStressRepository)

using namespace SG::DBManager::HDF5;
using namespace SG::DBManager;
using namespace SG::DataStructure;

QUAD4IntegStressRepository::QUAD4IntegStressRepository (HDF5Database& database) : RepositoryBase (database)
{}

// 析构函数实现
QUAD4IntegStressRepository::~QUAD4IntegStressRepository ()
{}

void QUAD4IntegStressRepository::InitialDatasetInfo ()
{
    RegisterTableInfo<ResultDomainIndex> ("/OWN/INDEX/RESULT/IntegStress/QUAD4", PrimarykeyTable);
    RegisterTableInfo<SG::DataStructure::Common::Real> ("/OWN/SG/RESULT/IntegStress/QUAD4", DATA);
}
bool QUAD4IntegStressRepository::Add (SG::DataStructure::Common::Id subcaseId, std::vector<SG::DataStructure::Common::Real>& data)
{
    // 默认一次把所有数据都写进去了，写了SID 3,以后再也没有sid 3 了
    auto& PrimarytableInfo = GetDatasetInfo (PrimarykeyTable);
    auto& dataTableInfo    = GetDatasetInfo (DATA);

    std::vector<ResultDomainIndex> pushData = { { subcaseId,
                                                  static_cast<SG::DataStructure::Common::I64> (dataTableInfo.GetRowCount ()),
                                                  static_cast<SG::DataStructure::Common::I64> (data.size ()) } };

    WriteData (dataTableInfo, data);
    WriteData (PrimarytableInfo, pushData);

    return true;
}

bool QUAD4IntegStressRepository::FindBySubcaseId (SG::DataStructure::Common::Id subcaseId,
                                                  _OUT std::vector<SG::DataStructure::Common::Real>& data)
{
    std::vector<ResultDomainIndex> allIds;
    auto&                          PrimarytableInfo = GetDatasetInfo (PrimarykeyTable);
    auto&                          dataTableInfo    = GetDatasetInfo (DATA);
    GetDatabase ().GetFile ()->getDataSet (PrimarytableInfo.GetPath ()).read (allIds);
    for (auto& ids : allIds)
    {
        if (( SG::DataStructure::Common::I64 ) subcaseId == ids.DOMAIN_ID)
        {
            GetDatabase ()
                .GetFile ()
                ->getDataSet (dataTableInfo.GetPath ())
                .select ({ static_cast<std::size_t> (ids.POSITION) }, { static_cast<std::size_t> (ids.LENGTH) })
                .read (data);
            return true;
        }
    }
    return false;
}
